﻿using pHMb.Spectrogram;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace LungSoundWizard.ViewModel
{
    public class SelectSnippetViewModel : ObservableBase
    {
        RelayCommand _okCommand;
        public ICommand OkCommand
        {
            get
            {
                if (_okCommand == null)
                {
                    _okCommand = new RelayCommand(p => SetAverages(((IList)p).Cast<SpectrogramPane.XSelection>().ToList()),
                        p => p != null && ((IList)p).Count > 0);
                }
                return _okCommand;
            }
        }

        SpectrogramPane _spectrogram;
        public SpectrogramPane Spectrogram
        {
            get
            {
                if (_spectrogram == null)
                {
                    _spectrogram = new SpectrogramPane();
                    _spectrogram.NoUpdate = true;
                }

                return _spectrogram;
            }
        }

        public List<Classes.ReferenceSnippet> Snippets { get; set; }

        AudioProcessor _audioProcessor;

        public SelectSnippetViewModel(string path)
        {
            Snippets = new List<Classes.ReferenceSnippet>();

            Spectrogram.Divisor = 130;
            Spectrogram.isGreyScale = false;
            
            Spectrogram.ScaleGraph = true;

            _audioProcessor = new AudioProcessor(Spectrogram);

            _audioProcessor.LoadWave(path);
        }

        void SetAverages(List<SpectrogramPane.XSelection> selections)
        {
            foreach (KeyValuePair<string, double[]> avgFftKvp in 
                SoundSelectionHandler.GenerateAverageFFT(selections, SoundSelectionHandler.AverageFftTypes.SNR))
            {
                Snippets.Add(new Classes.ReferenceSnippet()
                {
                    Name = avgFftKvp.Key,
                    AvgFft = avgFftKvp.Value
                });
            }
        }
    }
}
